package com.study.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.study.common.AjaxResult;
import com.study.common.DatagridReq;
import com.study.common.DatagridResp;
import com.study.entity.Goods;
import com.study.enums.StateEnum;
import com.study.service.IGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("goods")
public class GoodsController {
    @Autowired
    private IGoodsService goodsService;
    @RequestMapping("list")
    @ResponseBody
    public DatagridResp<Goods> list(DatagridReq req){
        Boolean isAsc= "asc".equals(req.getOrder())?true:false;
        Page<Goods> page = goodsService.selectPage(
                new Page<Goods>(req.getPage(), req.getRows()),
                new EntityWrapper<Goods>().orderBy(req.getSort(), isAsc));
        DatagridResp<Goods> resp=new DatagridResp<Goods>();
        resp.setRows(page.getRecords());
        resp.setTotal(page.getTotal());
        return resp;
    }
    @PatchMapping("update")
    @ResponseBody
    public AjaxResult update(@RequestBody Goods goods){
        boolean update = goodsService.updateById(goods);
        return update?new AjaxResult(StateEnum.UPDATE_SUC):new AjaxResult(StateEnum.UPDATE_FAIL);
    }
    @PostMapping("delete/{gid}")
    @ResponseBody
    public AjaxResult delete(@PathVariable Integer gid){
        return goodsService.deleteById(gid)?new AjaxResult(StateEnum.DELETE_SUC):new AjaxResult(StateEnum.DELETE_FAIL);
    }
    @PostMapping("add")
    @ResponseBody
    public AjaxResult add(Goods goods){
        boolean insert = goodsService.insert(goods);
        return insert?new AjaxResult(StateEnum.ADD_SUC):new AjaxResult(StateEnum.ADD_FAIL);
    }

}
